//
//  BIZRapidConsultResultVC.m
//  biz
//
//  Created by 小龙 on 2017/3/21.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZRapidConsultResultVC.h"
#import "BIZRapidAnswerCell.h"
#import "BIZAddQuetionVC.h"
#import "BIZRapidQuestionCell.h"
#import "BIZAnswerModel.h"
#import "BIZQuestionModel.h"
#import "BIAppraiseViewController.h"

@interface BIZRapidConsultResultVC ()<UIPopoverPresentationControllerDelegate,
                                      BIZBIZRapidAnswerCellDelegate>

/** 回答模型数组 */
@property (nonatomic, strong) NSMutableArray *answersArr;

@end

@implementation BIZRapidConsultResultVC

- (BOOL)shouldAutorotate {
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"咨询详情";
    
    [self setupTableView];
    
    if (self.alertTitleStr && self.alertTitleStr.length) {
        [UIAlertController showAlertViewWithTitle:self.alertTitleStr
                                          message:nil
                                cancelButtonTitle:@"关闭"
                               confirmButtonTitle:nil
                                      cancelBlock:nil
                                     confirmBlock:nil];
    }
    else {
        
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getAnswerListData)];
        self.tableView.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(getAnswerListData)];
        
        [self getAnswerListData];
    }

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.answersArr.count) {
        return 2;
    }
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!section) {
        return 1;
    }
    
    return self.answersArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section) {
        BIZRapidAnswerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZRapidAnswerCell" forIndexPath:indexPath];
        
        cell.answerModel = self.answersArr[indexPath.row];
        cell.delegate = self;
        
        if (([self.questionModel.status integerValue] == 1)
            ||([self.questionModel.status integerValue] == 4)) {
            cell.addQuestionBtn.hidden = YES;
            cell.adoptBtn.hidden = YES;
        }
        else {
            
            cell.adoptBtn.hidden = NO;
            
            
            if (cell.answerModel.stage <2) {
                cell.addQuestionBtn.hidden = NO;
            }
            else {
                cell.addQuestionBtn.hidden = YES;
            }

        }

        return cell;
    }
    
    BIZRapidQuestionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BIZRapidQuestionCell" forIndexPath:indexPath];
    cell.questionModel = self.questionModel;
    return cell;
}

- (void)setupTableView
{
    self.tableView.backgroundColor = HEXCOLOR(0xEEEDEE);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BIZRapidQuestionCell class]) bundle:nil] forCellReuseIdentifier:@"BIZRapidQuestionCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BIZRapidAnswerCell class]) bundle:nil] forCellReuseIdentifier:@"BIZRapidAnswerCell"];

    
    self.tableView.estimatedRowHeight = 500;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
}



- (void)getAnswerListData
{
    NSMutableDictionary *parmaDic = [NSMutableDictionary dictionary];
    parmaDic[@"uuid"] = self.questionModel.uuid;
    
    [MBProgressHUD showAnimationHUD];
    [RequestTool POST:kRapidAnswerListUrl
           parameters:parmaDic
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"responseObject---------:%@", responseObject);
//                  [MBProgressHUD hideHUD];
                  [self stopRefresh];
                  
                  BIZAnswerListModel *model = [BIZAnswerListModel yy_modelWithJSON:responseObject];
                  
                  if (model.code == 1) {
                      [MBProgressHUD hideHUD];
                      self.answersArr = [NSMutableArray arrayWithArray:model.answerArr];
                      
                      [self.tableView reloadData];
                  } else {
                      [MBProgressHUD showErrorMessage:model.des];
                      if (model.code == 2) {
                          BIZLoginViewController *vc = [BIZLoginViewController viewControllerFromStoryboard];
                          MPWeakSelf(self);
                          vc.loginSuccessBlock = ^(){
                              [weakself getAnswerListData];
                          };
                          [self presentViewController:vc animated:YES completion:nil];
                      }
                  }
                  
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  DeLog(@"error---------:%@",error);
                  [self stopRefresh];
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }

              }];
}


- (void)consultAnswerCellAdoptBtnClick:(BIZRapidAnswerCell *)cell
{
    [MBProgressHUD showActivityMessageInWindow:@"请稍后"];
    NSString *url = kAdoptAnswerUrl;
    NSMutableDictionary *parmaDic = [NSMutableDictionary dictionary];
    parmaDic[@"uuid"] = cell.answerModel.uuid;
    
    [RequestTool POST:url
           parameters:parmaDic
             progress:nil
              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  DeLog(@"responseObject---------:%@", responseObject);
                  
                  // MARK: WARNNING 采纳成功后如何处理

                  NSInteger code = [responseObject[@"code"] integerValue];
                  NSString *des = responseObject[@"des"];
                  if (code == 1) {
                      [MBProgressHUD showSuccessMessage:des];
                      [self getAnswerListData];
                      if (self.adoptBtnClickBlock) {
                          self.adoptBtnClickBlock();
                      }
                    
                      [self addChildViewController:[BIAppraiseViewController showWithURL:kAppraiseRapidConsultUrl uuid:(cell.answerModel.uuid) finishBlock:^{
                          [self.navigationController popViewControllerAnimated:YES];
                      }]];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:des];
                  }
                  
              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

                  DeLog(@"error---------:%@",error);
                  if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable) {
                      [MBProgressHUD showErrorMessage:@"网络不给力"];
                  }
                  else {
                      [MBProgressHUD showErrorMessage:@"服务器繁忙"];
                  }

              }];
}


- (void)stopRefresh
{
    !self.tableView.mj_header.isRefreshing ? : self.tableView.mj_header.endRefreshing;
    !self.tableView.mj_footer.isRefreshing ? : self.tableView.mj_footer.endRefreshing;
}



- (void)consultAnswerCellAddQuestionBtnClick:(BIZRapidAnswerCell *)cell
{
    MJWeakSelf;
    BIZAddQuetionVC *vc = [[BIZAddQuetionVC alloc]initWithUUID:cell.answerModel.uuid
                                                           url:kAddQuestionUrl
                                                    completion:^{
                                                        [weakSelf getAnswerListData];
                                                    }];
    BIZNavigationController *nav = [[BIZNavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
    DeLog(@"测试");
}


@end
